import Vue from 'vue'
import axios from 'axios'
import router from '../router/index'
import socket_m from '../util/connect'
const http = axios.create({
  baseURL: 'http://localhost:3000'
})

// 请求拦截
http.interceptors.request.use(config => {
  if (localStorage.token) {
    config.headers.Authorization = localStorage.token
  }
  return config
})

// 响应拦截
http.interceptors.response.use(res => {
  return res
}, err => {
  console.log(err.response);
  // Message.error(err.response.data)
})

// Vue.prototype.$http = http

function $ajax(url, method = 'get', data = {}, successMsg = true, errorMsg = true) {
  return new Promise(async (resolve, reject) => {
    const res = await http[method](url, data)
    if (!res.data) {
      errorMsg && Vue.prototype.$message.error('错误')
      resolve('404')
    }
    if (res.data.code === 0) {
      successMsg && res.data.msg && (Vue.prototype.$message.success(res.data.msg))
    } else if (res.data.code === 205) {
      errorMsg && res.data.msg && (Vue.prototype.$message.error('请登录 - ' + res.data.msg))
      // socket_m.closeServer()
      console.log('close');
      // router.push('/login').catch(err => {
      //   console.log(err);
      // })
    } else {
      errorMsg && res.data.msg && (Vue.prototype.$message.error(res.data.msg))
    }
    resolve(res.data)
  })
}

// Vue.prototype.$ajax = $ajax